<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Tomcat启动流程 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="tomcat 启动启动流程1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798">
<meta property="og:type" content="article">
<meta property="og:title" content="Tomcat启动流程">
<meta property="og:url" content="https://flyingzc.github.io/articles/tomcat/tomcat02-start.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="tomcat 启动启动流程1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2019-12-18T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.215Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Tomcat">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Tomcat启动流程",
  "url": "https://flyingzc.github.io/articles/tomcat/tomcat02-start.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2019-12-18T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.215Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/tomcat/tomcat02-start.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Tomcat启动流程',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">Tomcat启动流程</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">Tomcat启动流程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-12-18T16:00:00.000Z" title="发表于 2019-12-19 00:00:00">2019-12-19</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.215Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Tomcat/">Tomcat</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="tomcat-启动"><a href="#tomcat-启动" class="headerlink" title="tomcat 启动"></a>tomcat 启动</h1><h2 id="启动流程"><a href="#启动流程" class="headerlink" title="启动流程"></a>启动流程</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br></pre></td><td class="code"><pre><code class="hljs plaintext">- Bootstrap.main()<br>    - Bootstrap bootstrap = new Bootstrap(); 实例化Bootstrap实例<br>    - bootstrap.init(); 1.设置catalinaHome和catalinaBase 2.初始化类加载器,实例化**ClassLoaders<br>        - setCatalinaHome(); 设置Catalina path,System.getProperty(&quot;catalina.home&quot;),值为tomcat根目录<br>        - setCatalinaBase(); 值为D:\workspace-e3\.metadata\.plugins\org.eclipse.wst.server.core\tmp2<br>        - initClassLoaders(); 实例化**ClassLoaders，创建URLClassLoader<br>            - 初始化classloader,第二个参数为父classLoader commonLoader = createClassLoader(&quot;common&quot;, null); catalinaLoader = createClassLoader(&quot;server&quot;, commonLoader); sharedLoader = createClassLoader(&quot;shared&quot;, commonLoader); 最终执行结果是,创建了commonLoader,catalinaLoader 和 sharedLoader,其中 catalinaLoader 和 sharedLoader 默认均使用 父classLoader: 即 commonLoader<br>                - bootstrap.createClassLoader()<br>                    - 读取配置文件中配置的仓库路径(需要加载的jar包的路径) CatalinaProperties.getProperty(name + &quot;.loader&quot;);<br>                        - CatalinaProperties类中静态块中 static &#123;loadProperties();&#125; 后续从properties中取<br>                            - loadProperties()方法, 读取catalina.base\\conf\\catalina.properties配置文件到prop属性中 D:\workspace-e3\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\conf\catalina.properties<br>                    - bootstrap.replace()将$&#123;catalina.home&#125;等替换成具体的路径<br>                    - 根据逗号截取出每个资源路径<br>                    - URL url = new URL(repository); 先判断是不是网络资源,即先尝试使用URL加载,若它是网络资源则能加载成功, 否则捕获异常接着下面使用本地加载<br>                    - 本地加载.根据路径结尾以*.jar,.jar或路径,创建不同类型的repository对象<br>                        - RepositoryType枚举类分类<br>                            - DIR,// 表示整个目录下的资源,包括所有Class,Jar包以及其他类型资源<br>                            - GLOB,// 表示整个目录下所有的Jar包资源,仅仅是.jar后缀的资源<br>                            - JAR,// 表示单个Jar包资源<br>                            - URL// 表示从URL上获取的Jar包资源<br>                    - 根据以上的repository列表创建classLoader. ClassLoaderFactory.createClassLoader(repositories, parent)<br>                        - 遍历repositories,判断repositoryType.目的是将每种资源转换为new URL(),并添加到URL[]数组中 <br>                        0.若是RepositoryType.URL类型的资源,直接new一个URL实例即可 <br>                        1.若是DIR类型,则根据路径创建java.net.URL对象; <br>                        2.若是GLOB(这里是E:\Java\apache-tomcat-7.0.82-01\lib),则遍历该目录下的jar包,创建文件,每个jar文件对应一个URL对象;<br>                        - 最后根据以上所有的url,创建URLClassLoader并返回.该类构造器接收一个URL[]数组类型 return new URLClassLoader(array)<br>        - Thread.currentThread().setContextClassLoader(catalinaLoader); 为当前线程设置classLoader为catalinaLoader<br>        - 若启用了安全管理,则会在这里加载一些所需的包(默认不启用) SecurityClassLoad.securityClassLoad(catalinaLoader);<br>        - 使用catalinaLoader加载catalina类 Class&lt;?&gt; startupClass = catalinaLoader.loadClass(&quot;org.apache.catalina.startup.Catalina&quot;); Object startupInstance = startupClass.newInstance();<br>        - 设置catalina对象的parentClassLoader属性为sharedLoader, 由于前面sharedLoader默认使用的是父加载器commonLoader, 所以此处相当于设置为commonLoader org.apache.catalina.startup.Catalina.setParentClassLoader(sharedLoader);<br>        - bootstrap对象 保存catalina的引用 catalinaDaemon = startupInstance;<br>    - 处理&quot;start&quot;命令<br>        - 1.setAwait(true) 设置catalina.await=true<br>        - 2.daemon.load(args); 加载配置资源，通过反射调用catalina.load()方法 (1)创建digester实例,digester解析conf/server.xml文件 (2)调用Server.init()级联初始化各个组件<br>            - Catalina中 initDirs() 设置catalina.base和catalina.home和user.dir的property属性, 检查java.io.tmpdir属性是否存在<br>            - initNaming() 设置java.naming.factory.url.pkgs和java.naming.factory.initia这两个System.setProperty<br>            - 创建并执行digester,使用digester解析server.xml Digester digester = createStartDigester(); Digester类按照预定的规则解析server.xml，将元素转化为对象， 包括构造对象，set属性到对象字段，同时维护相互关联关系<br>                - new Digester() 创建digester对象<br>                - digester.addObjectCreate() 1)添加对象创建规则ObjectCreateRule 2)SetPropertiesRule 3)SetNextRule 添加StandardServer等各级容器的关系和处理规则<br>                - 创建Server实例,默认实现类是StandardServer, 可以通过server节点的className属性指定自己的实现,一般不需要<br>                - 设置Server属性<br>                - 调用setServer()将Server设置到Catalina对象中.可在本Catalina类中搜索setServer()方法<br>                - 创建JNDI实例对象,GlobalNamingResources,并设置其属性.并调用standServer.setGlobalNamingResources()方法装配到server中<br>                - 为Server添加生命周期监听<br>                - 创建service实例,创建完成后,通过addService()添加到server中<br>                - 为server添加生命周期监听器.默认未指定监听器,347行的null<br>                - 为service添加Executor<br>                - 为service添加Connector<br>                - 设置属性时,将executor属性排除在外.因为Connector创建时,即ConnectorCreateRule类中, 会判断当前是否指定了executor属性.若是,则从Service中查找该名称的executor并设置到Connector中.<br>                - 为Connector添加 生命周期监听器.默认未指定<br>                - 添加子元素解析规则.这部分指定了Servlet容器相关的各级嵌套子节点的解析规则. 且每类嵌套子节点的解析封装为一个RuleSet类(跟进去看).包括GlobalNamingResources,Engine,Context,Cluster的解析<br>            - 使用sax读取server.xml file = configFile();<br>            - digester.parse(inputSource); 使用digester解析读取的xml,在此过程中会初始化各个组件实例及其依赖关系. 最后会把server.xml文件中的内容解析到StandardServer中 (创建standServer对象并维护对象间关系)<br>                - configure();<br>                - getXMLReader().parse(input);<br>                    - ......<br>                        - 经过java里SAXPaser解析InputSource后,调用Digester.startElement()<br>                            - 遍历rules rule.begin(namespaceURI, name, list); 分别创建StandardServer实例<br>                                - new StandardServer()构造器<br>                                    - new NamingResources()<br>                                    - new NamingContextListener() addLifecycleListener(namingContextListener);<br>                                - setPropertiesRule()<br>                            - standardService.addConnector()<br>                            - standardServer.addService() 向server中添加一个新的service. digester在xml解析时会注入这个关系<br>                            - digester解析会做很多初始化操作,以后细化...<br>                            - Connector con = new Connector(attributes.getValue(&quot;protocol&quot;)); 创建Connector,会有多个Connector,和xml中配置的数量有关<br>                                - Connector构造器<br>                                    - setProtocol(protocol);<br>                                        - 根据xml配置的协议类型,此处是Http11Protocol setProtocolHandlerClassName (&quot;org.apache.coyote.http11.Http11Protocol&quot;);<br>                                    - 实例化Http11Protocol<br>                                        - Http11Protocol构造器<br>                                            - endpoint = new JIoEndpoint();<br>            - getServer().init(); 调用Server的init()方法,初始化各个组件. 它会调用各个service子容器的init()方法, 从而级联完成组件初始化 在调用init()时第3步,调用子类StandardService.initInternal(); 各个组件有个共同的父类: LifecycleBase,用于管理组件的生命周期和状态变化。 在走Server.init()前,先走父类LifecycleBase.init(),事件驱动当前组件状态的变化. 从StandardServer到StandardWrapper,都会调用initInternal(), 并伴随调用共有父类LifecycleBase.init()<br>                - init()方法在父类LifecycleBase中, 调用父类LifecycleBase.init()<br>                    - super.initInternal(); 即父类LifecycleBase.initInternal()<br>                        - 1.先判断状态是否为LifecycleState.NEW(默认是)  <br>                          2.LifecycleBase.setStateInternal(LifecycleState.INITIALIZING, null, false); 变更生命周期状态为LifecycleState.INITIALIZING 调用各个事件监听中的 初始化方法<br>                        - 3.initInternal();这个方法一般被子类覆盖,执行子类自己的逻辑 此处为StandServer.initInternal()<br>                            - StandServer.initInternal()中 super.initInternal(); 调用父类LifecycleMBeanBase.initInternal()<br>                                - LifecycleMBeanBase.initInternal()中 将容器托管到JMX，便于运维管理<br>                            - 遍历services调用service.init() services[i].init();<br>                                - StandardService.init()中 init()方法在父类LifecycleBase中, 调用父类LifecycleBase.init()<br>                                    - LifecycleBase.init()中 setStateInternal(LifecycleState.INITIALIZING, null, false); 变更生命周期状态为LifecycleState.INITIALIZING(通过事件变更)<br>                                    - initInternal();// 进入子类的initInternal()方法, 即调用StandardService.initInternal()<br>                                        - StandardService.initInternal()中 container.init(); 此处container即为StandardEngine.init()  StandardEngine的子容器standardContext及其子容器没有init初始化逻辑<br>                                            - StandardEngine.init()中,略去LifecycleBase中生命周期变更的重复逻辑 StandardEngine.initInternal()中 getRealm(); 创建realm<br>                                            - super.initInternal(); 即为ContainerBase.initInternal() Engine,Host,Context,Wrapper容器都拥有共同父类ContainerBase<br>                                                - ContainerBase.initInternal()中 startStopExecutor = new ThreadPoolExecutor() 初始化startStopExecutor,用于管理启动和关闭的线程<br>                                                - super.init()即LifecycleMBeanBase.initInternal()<br>                                                    - ......略去各个StandardHost.init()<br>                                                        - ...<br>                                                            - lifecycleBase.init()<br>                                                                - LifecycleBase.setStateInternal(LifecycleState.INITIALIZED, null, false);初始化完成 StandardContext父类LifecycleBase变更生命周期状态,调用各个事件监听中的 initializing<br>                                                                - initInternal();// 进入子类StandardContext.initInternal()方法<br>                                                                    - super.initInternal(); StandardContext.initInternal()调用父类ContainerBase.initInternal() 它会创建startStopExecutor 并调用父类LifecycleMBeanBase.initInternal(); 这里会将容器托管到JMX<br>                                                                    - this.addLifecycleListener(new TldConfig()); 添加TldConfig监听<br>                                                                - setStateInternal(LifecycleState.INITIALIZED, null, false); // 更新组件生命周期状态为LifecycleState.INITIALIZED<br>                                                                    - ...<br>                                                                        - contextConfig.lifecycleEvent() contextConfig AFTER_INIT_EVENT生命周期事件处理<br>                                                                            - contextConfig.init(); context初始化阶段,context属性配置 tomcat提供的默认配置添加到context实例 完成对应的 每个web应用项目的配置解析(web.xml)<br>                                                                                - createContextDigester()<br>                                                                                - contextDigester.getParser();<br>                                                                                - contextConfig(contextDigester);  解析config.xml配置 E:\Java\apache-tomcat-7.0.82-01\conf\context.xml<br>                                                                                - createWebXmlDigester()<br>                                                                            - beforeStart() Lifecycle.BEFORE_START_EVENT状态<br>                                        - executor.init(); 初始化executors,即tomcat间可共享的线程池<br>                                        - connector初始化<br>                                            - connector.initInternal();<br>                                                - adapter = new CoyoteAdapter(this); 构建与指定连接器关联的新CoyoteAdapter<br>                                                - protocolHandler.setAdapter(adapter); 给 协议处理器 添加 adapter<br>                                                - protocolHandler.init(); 初始化具体协议类型，如Http11Protocol协议<br>                                                    - AbstractHttp11JsseProtocol.init()<br>                                                        - endpoint初始化之前,需要初始化ssl实现类 sslImplementation = SSLImplementation.getInstance(sslImplementationName); return new org.apache.tomcat.util.net.jsse.JSSEImplementation();<br>                                                        - super.init(),即AbstractProtocol.init() 1.注册组件JIoEndPoint;  2.endpoint.init() 设置work threads的数量，默认为200，并创建serverSocket对象<br>                                                            - abstractProtocol.bind() 设置线程数,网络连接数<br>                                                                - 初始化acceptor线程数量,默认1个; 初始化最大连接数,此值为server.xml的connector元素的属性MaxThreads值，(若不设置则)默认200<br>                                                                - abstractEndpoint.getMaxThreadsWithExecutor() 返回成员变量maxThreads=200<br>                                                                - abstractEndpoint.setMaxConnections(getMaxThreadsWithExecutor()); 设置最大连接数<br>                                                                    - initializeConnectionLatch(); 创建LimitLatch对象并初始化连接数 即 connectionLimitLatch = new LimitLatch(getMaxConnections());<br>                                                                - serverSocketFactory = new DefaultServerSocketFactory(this); 创建ServerSocketFactory<br>                                                                - serverSocket = serverSocketFactory.createSocket(getPort(),getBacklog()); 创建serverSocket<br>                                                - 初始化mapper listener mapperListener.init();<br>                        - 容器初始化完毕，LifecycleBase会将容器的状态更改为初始化完毕 setStateInternal(LifecycleState.INITIALIZED, null, false);<br>        - 3.daemon.start().即catalina.start() 运行各个组件,容器开始启动.<br>            - getServer().start() 启动Server 即standardServer.start(),由于未重写该方法. 所以会先调用父类LifecycleBase.start()<br>                - LifecycleBase.start()中 setStateInternal(LifecycleState.STARTING_PREP, null, false); // 启动前将状态设置为LifecycleState.STARTING_PREP<br>                - startInternal(); // 模板方法调用子类逻辑<br>                    - StandardServer.startInternal();中 1.发布configure_start事件 fireLifecycleEvent(CONFIGURE_START_EVENT, null);<br>                    - 2.设置状态为starting setState(LifecycleState.STARTING);  3.globalNamingResources.start(); globalNamingResources.start();<br>                    - 4.services[i].start(); 启动多个Service子容器. 略去LifecycleBase.start()的重复逻辑, 调用standardService.startInternal()<br>                        - standardService.startInternal()中 container.start(): 启动container,此时container为StandardEngine<br>                            - StandardEngine.startInternal()中 调用super.startInternal(), 即ContainerBase.startInternal()<br>                                - ContainerBase.startInternal()中 若配置了loader,manager,cluster,realm等,则会启动这些下属组件.  在engine,host,context等容器的启动逻辑都会调用该父类(ContainerBase)的此方法用于加载启动子容器. containerBase.startInternal()会向线程池 提交启动子容器的任务,并阻塞等待子容器启动的返回结果判定是否启动成功<br>                                    - ContainerBase.startInternal()中 getLoaderInternal()<br>                                        - Lock readLock = loaderLock.readLock(); readLock.lock(); try &#123;     return loader; &#125; finally &#123;     readLock.unlock(); &#125;<br>                                    - 若配置了realm组件,则启动 Realm realm = getRealmInternal();  if ((realm != null) &amp;&amp; (realm instanceof Lifecycle))      ((Lifecycle) realm).start();<br>                                    - 若有子容器,则启动 Container children[] = findChildren();<br>                                    - results.add(startStopExecutor.submit(new StartChild(children[i]))); 提交启动子容器的任务,后续StandHost的操作会在新线程中完成<br>                                        - StartChild.call() class StartChild implements Callable&lt;Void&gt; StartChild类实现Callable,会执行覆写的call()方法<br>                                            - child.start(); 启动子容器,比如此处Engine的子容器就是Host 即调用standHost.start()<br>                                                - StandardHost.start() 使用父类LifecycleBase中的start()方法<br>                                                    - LifecycleBase.start()中<br>                                                        - LifecycleBase.start()中 setStateInternal(LifecycleState.STARTING_PREP, null, false); 触发before_start事件,即Host容器发布before_start事件, 相关监听器会接收到通知,执行相应逻辑,如HostConfig监听器<br>                                                            - HostConfig.lifecycleEvent() HostConfig实现LifecycleListener接口,在StandardHost启动时生命周期发生变化时, 会调用HostConfig的lifecycleEvent()对特定事件进行逻辑处理<br>                                                                - 调用HostConfig.beforeStart() BEFORE_START_EVENT<br>                                                                    - beforeStart() 会创建appBase和configBase路径所需的目录<br>                                                                        - 判断host.getCreateDirs(),对appBase和configBase进行mkdirs()<br>                                                        - lifecycleBase.startInternal(); 会调用子类StandardHost.startInternal()<br>                                                            - StandardHost.startInternal()中 Valve[] valves = getPipeline().getValves();<br>                                                                - 获取错误阀的阀名,即org.apache.catalina.valves.ErrorReportValve getErrorReportValveClass()<br>                                                                - 若有错误阀名,尝试遍历所有阀找出这个class类 StandardPipline.getValues() 通过value.getNext()循环遍历将所有Value成数组返回<br>                                                                - 若没有找到,则反射创建实例,并添加到pipeline中<br>                                                            - super.startInternal(); 调用ContainerBase.startInternal()新起线程启动子容器(即Host的Context子容器)<br>                                                                - ContainerBase.startInternal()中 results.add(startStopExecutor.submit(new StartChild(children[i]))); 启动StandardContext!!!!!!后续子节点都是Context容器的操作<br>                                                                    - 调用StandardContext.start(), 由于该类未重写start(), 所以实际上调用父类lifecycleBase.start()<br>                                                                        - lifecycleBase.start()中 若是LifecycleState.NEW状态<br>                                                                        - LifecycleBase.setStateInternal(LifecycleState.STARTING_PREP, null, false); 设置LifecycleState.STARTING_PREP状态,即before_start<br>                                                                            - 调用ContextConfig.beforeStart(); // 在context启动前触发,用于更新Context的docBase属性 和 解决web目录锁的问题<br>                                                                        - LifecycleBase.startInternal();<br>                                                                            - 调用子类StandardContext.startInternal() 完成对web应用的初始化工作<br>                                                                                - StandardContext.startInternal()里经过一系列操作,将状态变更为CONFIGURE_START_EVENT standardContext.fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null); 发布CONFIGURE_START_EVENT事件,contextConfig监听以完成servlet创建<br>                                                                                    - contextConfig.configureStart(); web应用初始化.解析web.xml文件, 创建wrapper,Filter,ServletContextListener等.<br>                                                                                        - contextConfig.webConfig()<br>                                                                                            - webXml.configureContext(context); 解析web.xml,将webXml对象设置给context<br>                                                                                                - Lin1388 webXml.configureContext(context); 解析servlet,将Servlet包装成Wrapper<br>                                                                                                    - context.createWrapper()<br>                                                                                                    - wrapper.setServletClass(servlet.getServletClass()); 将wrapper与servlet绑定<br>                                                                                                    - context.addChild(wrapper); 将wrapper添加到context中<br>                                                                                                        - containerBase.addChildInternal(child);<br>                                                                                                            - child.start(); 即standardWraper.start()<br>                                                                                                                - Wrapper容器 StandardWrapper.start()<br>                                                                        - LifecyclesetStateInternal(LifecycleState.STARTED, null, false); 设置LifecycleState.STARTED状态,即after_start<br>                                                                            - 调用context.setDocBase(originalDocBase);<br>                                                                        - containerBase.threadStart(); 启动Context层级的后台任务进程.Cluster后台任务(包括部署变更检测,心跳).Pipeline中Value的后台任务处理(如果有定时处理任务)<br>                                                                - ContainerBase.startInternal()中 setState(LifecycleState.STARTING); 设置容器状态为STARTING,此时会触发START_EVENT生命周期事件.即start事件<br>                                                                    - 调用HostConfig.start(); Host启动时触发,完成服务器启动过程中的 Web应用部署. 需要 Host的deployOnstartup=&quot;true&quot;才会在服务器启动时部署web应用. <br>                                    - 若有管道,则启动 if (pipeline instanceof Lifecycle)     ((Lifecycle) pipeline).start();<br>                        - executor.start(); 启动service容器的多个线程池executors<br>                        - connector.start(); 启动service组件的多个connector<br>                            - connector.startInternal()<br>                                - protocolHandler.start(); 启动 协议处理器<br>                                    - endpoint.start();<br>                                        - createExecutor(); 创建endpoint私有的线程池,即ThreadPoolExecutor线程池<br>                                            - abstractEndpoint.createExecutor()<br>                                                - new TaskQueue(); 用来运行线程池执行器的任务队列,该类extends LinkedBlockingQueue&lt;Runnable&gt;  new TaskThreadFactory()  implements ThreadFactory 线程工厂,用于创建并返回线程  executor = new ThreadPoolExecutor() 根据前两者 创建线程池<br>                                        - initializeConnectionLatch(); 创建LimitLatch对象,之前init时已经创建.此处直接返回<br>                                        - startAcceptorThreads(); 创建多个Acceptors<br>                                            - getAcceptorThreadCount(); 获取acceptor线程数量,默认1<br>                                            - return new JIoEndpoint.Acceptor() implements Runnable; 创建JIoEndpoint<br>                                            - Thread t = new Thread(acceptors[i], threadName); 根据JIoEndpoint创建线程,且是守护线程<br>                                - mapperListener.start(); 启动 mapperListener<br>                                    - findDefaultHost(); 从engine中获取defaultHost并设置给mapper<br>                                        - 从engine中获取defaultHost并设置给mapper mapper.setDefaultHostName(defaultHost);<br>                                    - addListeners(engine);<br>                                        - container.addContainerListener(this); container.addLifecycleListener(this); addListeners(child); 其中this为engine,child为host.即给engine注册监听<br>                                    - registHost() 向mapper注册host及其下的context,wrapper<br>                                        - mapper.addHost(host.getName(), aliases, host);<br>                                        - registerContext((Context) container); 向mapper注册context<br>                                            - prepareWrapperMappingInfo(context, (Wrapper) container, wrappers);<br></code></pre></td></tr></table></figure>
<h2 id="bootstrap-init"><a href="#bootstrap-init" class="headerlink" title="bootstrap.init()"></a>bootstrap.init()</h2><p>创建 commonClassLoader,和 两个子 类加载器 catalinaLoader 和 sharedLoader,当然都是 URLClassLoader 实例,加载 一些 Jar.</p>
<p>设置当前线程的上下文类加载器为 catalinaLoader</p>
<p>设置 Catalina 的 父类加载器为 sharedLoader</p>
<h2 id="处理-start-命令"><a href="#处理-start-命令" class="headerlink" title="处理 start 命令"></a>处理 start 命令</h2><p>分为 load 和 start 两步</p>
<h3 id="load"><a href="#load" class="headerlink" title="load"></a>load</h3><p>读取 conf&#x2F;server.xml 配置,使用 digester 解析,组装对象.</p>
<p>server.init() 主要遍历 services,调用其 init() 方法<br>状态变更: LifecycleState.NEW -&gt; LifecycleState.INITIALIZING -&gt; initInternal() -&gt; LifecycleState.INITIALIZED</p>
<p>service.init()<br>调用 engine.init(),初始化executor,遍历初始化 connectors</p>
<p>Connector.init()<br>创建 CoyoteAdapter<br>protocolHandler 关联 adapter<br>protocolHandler.init(),这里面会初始化 endpoint<br>mapperListener.init()</p>
<p>StandEngine.init()<br>engine,host,context,wrapper 都继承自 ContainerBase,ContainerBase里会起 startStopExecutor 线程池,这个线程池用于子容器启动,父容器会等待子容器启动完成.</p>
<h3 id="start"><a href="#start" class="headerlink" title="start"></a>start</h3><p>Catalina.start()<br>调用 server.start()</p>
<p>StandardServer.start()<br>触发 CONFIGURE_START_EVENT 事件,设置自身的状态为 STARTING,遍历调用 services.start()</p>
<p>StandService.start()<br>设置状态为 STARTING,调用 engine.start(),excutors.start(),connector.start()</p>
<p>StandEngine.start()<br>会走父类 ContainerBase.startInternal(),在 ContainerBase 中,若配了 loader,manager, cluster, realm 则 启动.<br>然后就查找所有子容器,每个子容器都交由 startStopExecutor 线程池 执行 StartChild 的逻辑,调用 child.start().并通过 future.get() 阻塞等待所有子容器启动成功.<br>pipeline.start()<br>设置线程状态为 STARTING,触发 START_EVENT 生命周期事件.<br>启动一个 ContainerBackgroundProcessor 后台线程.</p>
<p>ContainerBase.startInternal()代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">protected</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">startInternal</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> LifecycleException &#123;<br>    <span class="hljs-comment">// Start our subordinate components, if any.启动下属组件</span><br>    <span class="hljs-type">Loader</span> <span class="hljs-variable">loader</span> <span class="hljs-operator">=</span> getLoaderInternal();<br>    <span class="hljs-keyword">if</span> ((loader != <span class="hljs-literal">null</span>) &amp;&amp; (loader <span class="hljs-keyword">instanceof</span> Lifecycle))<span class="hljs-comment">// 若配置了loader则启动</span><br>        ((Lifecycle) loader).start();<br>    logger = <span class="hljs-literal">null</span>;<br>    getLogger();<br>    <span class="hljs-type">Manager</span> <span class="hljs-variable">manager</span> <span class="hljs-operator">=</span> getManagerInternal();<br>    <span class="hljs-keyword">if</span> ((manager != <span class="hljs-literal">null</span>) &amp;&amp; (manager <span class="hljs-keyword">instanceof</span> Lifecycle))<br>        ((Lifecycle) manager).start();<br>    <span class="hljs-type">Cluster</span> <span class="hljs-variable">cluster</span> <span class="hljs-operator">=</span> getClusterInternal();<br>    <span class="hljs-keyword">if</span> ((cluster != <span class="hljs-literal">null</span>) &amp;&amp; (cluster <span class="hljs-keyword">instanceof</span> Lifecycle))<span class="hljs-comment">// 若配置了集群,则启动</span><br>        ((Lifecycle) cluster).start();<br>    <span class="hljs-type">Realm</span> <span class="hljs-variable">realm</span> <span class="hljs-operator">=</span> getRealmInternal();<br>    <span class="hljs-keyword">if</span> ((realm != <span class="hljs-literal">null</span>) &amp;&amp; (realm <span class="hljs-keyword">instanceof</span> Lifecycle))<span class="hljs-comment">// 若配置了安全组件Realm,则启动</span><br>        ((Lifecycle) realm).start();<br>    <span class="hljs-type">DirContext</span> <span class="hljs-variable">resources</span> <span class="hljs-operator">=</span> getResourcesInternal();<br>    <span class="hljs-keyword">if</span> ((resources != <span class="hljs-literal">null</span>) &amp;&amp; (resources <span class="hljs-keyword">instanceof</span> Lifecycle))<br>        ((Lifecycle) resources).start();<br><br>    <span class="hljs-comment">// Start our child containers, if any.启动子容器,如果有的话.</span><br>    Container children[] = findChildren();<br>    List&lt;Future&lt;Void&gt;&gt; results = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span>&lt;Future&lt;Void&gt;&gt;();<br>    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i &lt; children.length; i++) &#123; <span class="hljs-comment">// 提交 启动子容器的任务.并阻塞当前线程等待执行结果</span><br>        results.add(startStopExecutor.submit(<span class="hljs-keyword">new</span> <span class="hljs-title class_">StartChild</span>(children[i]))); <span class="hljs-comment">// 子容器使用 startStopExecutor 调用新线程来启动</span><br>    &#125;<br><br>    <span class="hljs-type">boolean</span> <span class="hljs-variable">fail</span> <span class="hljs-operator">=</span> <span class="hljs-literal">false</span>;<br>    <span class="hljs-keyword">for</span> (Future&lt;Void&gt; result : results) &#123; <span class="hljs-comment">// 启动 多个子容器的执行结果</span><br>        <span class="hljs-keyword">try</span> &#123;<br>            result.get(); <span class="hljs-comment">// 阻塞直到所有子容器启动完毕</span><br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            log.error(sm.getString(<span class="hljs-string">&quot;containerBase.threadedStartFailed&quot;</span>), e);<br>            fail = <span class="hljs-literal">true</span>;<br>        &#125;<br><br>    &#125;<br>    <span class="hljs-keyword">if</span> (fail) &#123;<br>        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">LifecycleException</span>(<br>                sm.getString(<span class="hljs-string">&quot;containerBase.threadedStartFailed&quot;</span>));<br>    &#125;<br><br>    <span class="hljs-comment">// Start the Valves in our pipeline (including the basic), if any.启动容器持有的Pipeline组件的Value.若有管道,则启动</span><br>    <span class="hljs-keyword">if</span> (pipeline <span class="hljs-keyword">instanceof</span> Lifecycle)<br>        ((Lifecycle) pipeline).start();<br><br>    <span class="hljs-comment">// 设置容器状态为STARTING,此时会触发START_EVENT生命周期事件.</span><br>    setState(LifecycleState.STARTING);<br><br>    <span class="hljs-comment">// Start our thread. 启动该层级的后台定时任务进程(不同容器调用,则启动不同容器的后台线程).用于处理如 Cluster 后台任务(包括部署变更检测,心跳).Realm 后台任务处理.Pipeline 中 Value 的后台任务处理(如果有定时处理任务)</span><br>    threadStart();<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>StandardHost.startInternal()<br>不存在errorValve则创建,调用 ContainerBase.startInternal() 启动子容器.子容器是在 HostConfig.deployXxx里通过<code>host.addChild(context)</code>添加进来的.</p>
<p>StandContext.startInternal()<br>创建 WebappLoader 并启动<br>触发 CONFIGURE_START_EVENT 事件,contextConfig 监听以完成 servlet 创建<br>遍历启动子容器<br>启动pipline<br>触发listener的各种事件<br>初始化filter<br>初始化servlets,调用 load-on-startup 的 servlet 的 init() 方法<br>遍历 wraper,调用 wrapper.load() 加载 wrapper</p>
<p>StandWrapper.startInternal()<br>没什么重要逻辑</p>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/tomcat/tomcat02-start.html">https://flyingzc.github.io/articles/tomcat/tomcat02-start.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Tomcat/">Tomcat</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/tomcat/tomcat01-lifecycle.html" title="Tomcat Lifecycle"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-19</div><div class="info-item-2">Tomcat Lifecycle</div></div><div class="info-2"><div class="info-item-1">LifeCycleLifeCycle 相关类LifeCycle 接口中的状态扭转注释,如下: 12345678910111213141516171819202122232425262728*            start()*  -----------------------------*  |                           |*  | init()                    |* NEW -»-- INITIALIZING        |* | |           |              |     ------------------«-----------------------* | |           |auto          |     |                                        |* | |          \|/    start() \|/   \|/     auto          auto         stop() |* | |     ...</div></div></div></a><a class="pagination-related" href="/articles/tomcat/tomcat01_debug.html" title="Tomcat Debug"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-29</div><div class="info-item-2">Tomcat Debug</div></div><div class="info-2"><div class="info-item-1">tomcat debug方式1. tomcat远程debug,这种方式正常用于sit或者灰度环境调试问题使用,当然localhost也能这样debug.在 startup.sh 中配置 1SET CATALINA_OPTS=-server -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=19999  方式2. 在idea中启动tomcat debug,需要添加tomcat的jar依赖.这种方式用于本地看tomcat源码或者定位本地起的项目中tomcat部分的问题时可以使用. 12345678910111213&lt;dependency&gt;    &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt;    &lt;artifactId&gt;tomcat-catalina&lt;/artifactId&gt;    &lt;version&gt;7.0.82&lt;/version&gt;...</div></div></div></a><a class="pagination-related" href="/articles/tomcat/tomcat03-session.html" title="Tomcat Session机制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-20</div><div class="info-item-2">Tomcat Session机制</div></div><div class="info-2"><div class="info-item-1">tomcat session相关类12345org.apache.catalina.ManagerStandardManagerSessionIdGenerator  Manager实现类Manager 用于管理 session.默认实现是 StandardManager,基类 ManagerBase. 123456789101112Manager    ClusterManager (org.apache.catalina.ha)        ClusterManagerBase (org.apache.catalina.ha.session)            BackupManager (org.apache.catalina.ha.session)            DeltaManager (org.apache.catalina.ha.session)    ManagerBase (org.apache.catalina.session)        PersistentManagerBase (org.apache.catalina.session)...</div></div></div></a><a class="pagination-related" href="/articles/tomcat/tomcat04-distribute-session.html" title="Tomcat实现分布式session"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-20</div><div class="info-item-2">Tomcat实现分布式session</div></div><div class="info-2"><div class="info-item-1">tomcat实现分布式sessiontomcat-redis-session-manager 使用Copy the following files into the TOMCAT_BASE&#x2F;lib directory: 123tomcat-redis-session-manager-VERSION.jarjedis-2.5.2.jarcommons-pool2-2.2.jar  配置 TOMCAT_HOME&#x2F;conf&#x2F;context.xml 12345&lt;Valve className=&quot;com.radiadesign.catalina.session.RedisSessionHandlerValve&quot; /&gt;&lt;Manager className=&quot;com.radiadesign.catalina.session.RedisSessionManager&quot;         host=&quot;localhost&quot;            port=&quot;6379&quot;...</div></div></div></a><a class="pagination-related" href="/articles/tomcat/tomcat06-request.html" title="Tomcat处理请求流程"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-26</div><div class="info-item-2">Tomcat处理请求流程</div></div><div class="info-2"><div class="info-item-1">tomcat处理请求组件Server123456789101112131415Server|-- Service|--|-- Connector|--|--|-- Prototal|--|--|--|-- Endpoint|--|--|--|--|-- Acceptor|--|--|--|--|-- Executor|--|--|--|-- Processor|--|--|-- Mapper|--|--|-- CoyteAdapter|--|-- Container|--|--|--|-- Host|--|--|--|-- Context|--|--|--|-- Wrapper|--|-- Executor  Http11NioProtocol12345678910111213Http11NioProtocol|-- NioEndpoint|--|-- LimitLatch|--|-- Acceptor|--|-- Poller|--|-- Poller池|--|-- SocketProcessor|--|-- Executor|--|-- PollerEvent|--|--...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#tomcat-%E5%90%AF%E5%8A%A8"><span class="toc-number">1.</span> <span class="toc-text">tomcat 启动</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%AF%E5%8A%A8%E6%B5%81%E7%A8%8B"><span class="toc-number">1.1.</span> <span class="toc-text">启动流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#bootstrap-init"><span class="toc-number">1.2.</span> <span class="toc-text">bootstrap.init()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%84%E7%90%86-start-%E5%91%BD%E4%BB%A4"><span class="toc-number">1.3.</span> <span class="toc-text">处理 start 命令</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#load"><span class="toc-number">1.3.1.</span> <span class="toc-text">load</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#start"><span class="toc-number">1.3.2.</span> <span class="toc-text">start</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>